package test.ground.netty.netty.my;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 服务端监控读事件超时,关闭连接
 */
public class ServerHeartBeatHandler extends ChannelInboundHandlerAdapter {

    //当服务器5秒内没有发生读的事件时，会触发这个事件
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) { //当事件为读事件触发时发生异常，或者中断
                throw new Exception("idle exception");//将通道进行关闭
            }
        }else {
            super.userEventTriggered(ctx, evt);
        }
    }
    //当通道有读事件时
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        System.out.println("server channelRead..");
//        System.out.println(ctx.channel().remoteAddress() + "->Server :" + msg.toString());
        if(((Message)msg).isBiz()){
            ctx.fireChannelRead(msg);
        }
    }

    //当通道发生异常时
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("server happend exception ,server close channel :"+cause.getMessage());
        ctx.close();
    }
}